package controllers

import (
	"beegoProject17/models/auth"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type HomeController struct {
	beego.Controller
}

func (c *HomeController) Get() {

	o := orm.NewOrm()

	userId := c.GetSession("id")

	user := auth.User{
		Id: userId.(int),
	}
	o.LoadRelated(&user, "Role")

	authArr := []int{}
	for _, role := range user.Role {
		roleData := auth.Role{
			Id: role.Id,
		}
		o.LoadRelated(&roleData, "Auth")
		for _, authData := range roleData.Auth {
			authArr = append(authArr, authData.Id)
		}
	}

	qs := o.QueryTable("sys_auth")

	auths := []auth.Auth{}
	// 1 升序排列 .OrderBy("数据库字段")  / 降序 .OrderBy("-数据库字段")
	qs.Filter("pid", 0).Filter("id__in", authArr).OrderBy("-weight").All(&auths)

	trees := []auth.Tree{}

	for _, authData := range auths {
		pid := authData.Id
		treeData := auth.Tree{
			Id:       authData.Id,
			AuthName: authData.AuthName,
			UrlFor:   authData.UrlFor,
			Weight:   authData.Weight,
			Children: []*auth.Tree{},
		}
		GetChildNode(pid, &treeData)
		trees = append(trees, treeData)
	}

	o.QueryTable("sys_user").Filter("id", userId).One(&user)
	c.Data["user"] = user
	c.Data["trees"] = trees
	c.TplName = "index.html"
}

func (c *HomeController) Welcome() {
	c.TplName = "welcome.html"
}

// GetChildNode  6. 定义GetChildNode
func GetChildNode(pid int, treeNode *auth.Tree) {

	// 8.查询出全部的二级菜单，存入auths内
	o := orm.NewOrm()
	qs := o.QueryTable("sys_auth")
	auths := []auth.Auth{}
	_, err := qs.Filter("pid", pid).OrderBy("-weight").All(&auths)
	if err != nil {
		return
	}

	// 9. 循环auths继续查询三级及以上的菜单
	for i := 0; i < len(auths); i++ {
		pids := auths[i].Id // 根据pid获取所有子节点

		// 10. 初始化
		treeData := auth.Tree{
			Id:       auths[i].Id,
			AuthName: auths[i].AuthName,
			UrlFor:   auths[i].UrlFor,
			Weight:   auths[i].Weight,
			Children: []*auth.Tree{},
		}

		// 12. 追加写入Children
		treeNode.Children = append(treeNode.Children, &treeData)

		// 11. 调用 GetChildNode
		GetChildNode(pids, &treeData)
	}

	return
}
